// 下载小程序二维码的工具js
import request from 'request';
import fs from 'fs';
import path from 'path';
import os from 'os';
import uuid from 'uuid';
import { transImageUrlToBuffer } from '../txCosUpload';
import { getWxAccountToken } from './token';

const ADD_IMAGE_INTERFACE = 'https://api.weixin.qq.com/cgi-bin/media/upload';

/**
 * 新增微信临时素材
 * 返回 media_id
 */
export async function addWxImage(imgUrl) {
  const token = await getWxAccountToken(true);
  const file = await transImageUrlToBuffer(imgUrl);
  // 将文件临时存储在本地
  const tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), `./${uuid.v1()}`));
  const filePath = path.join(tmpdir, 'img.png');
  fs.appendFileSync(filePath, file);

  return new Promise((resolve, reject) => {
    /**
     * 请求微信服务器
     * 请求方式以及参数说明见
     * 文档 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-scheme/urlscheme.generate.html
     */
    request(
      {
        method: 'POST',
        url: `${ADD_IMAGE_INTERFACE}?access_token=${token}&type=image`,
        formData: {
          media: fs.createReadStream(filePath)
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
      },
      (error, response, body) => {
        if (error) {
          console.log('接口地址', `${ADD_IMAGE_INTERFACE}?access_token=${token}&type=image`);
          console.log('微信接口请求失败', error);
          reject(error);
          return;
        }
        console.log('新增微信临时素材', body);
        try {
          const res = JSON.parse(body);
          resolve(res.media_id || '');
        } catch (err) {
          reject(err);
        }
      }
    );
  });
}
